from sanic import Sanic,response
from sanic.response import stream
import asyncio
from asyncio.subprocess import PIPE, STDOUT

asyncio.set_event_loop_policy(
    asyncio.WindowsProactorEventLoopPolicy())
app = Sanic(__name__)

async def get_lines():
    # print('before')
    # await asyncio.sleep(3)
    # print('after')

    print('before')
    p = await asyncio.create_subprocess_shell('python -u outputs.py',
            stdout=PIPE, stderr=PIPE)
    print('after')
    while not p.stdout.at_eof():
        data = await p.stdout.readline()
        line = data.decode('ascii').rstrip()
        print(line)
        # if line == '':
        #     break

    print(await p.communicate())
    print('finish')
    # return (await p.communicate())[0]

@app.route("/")
async def test(request):
    # print(request.app.loop)
    # myLoop = request.app.loop
    # myLoop.create_task(get_lines())
    # return response.json({'hello':'world'})

    # # async def sample_streaming_fn(response):
    # #     await get_lines('python outputs.py')
    # #     # await response.write('foo,')
    # #     # await response.write('bar')
    # #
    # # return stream(sample_streaming_fn, content_type='text/csv')

    #######################################################################
    app.add_task(get_lines())
    return response.json({'hello':'world'})


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)

